package br.com.projeto.managedbeans;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.projeto.entities.User;
import br.com.projeto.rulebusiness.UserRB;
import br.com.projeto.util.AuthFilter;

@ManagedBean
@SessionScoped
public class LoginUserBean {

	private User user 		= new User(); 
	private User userLogin	= new User();
	
	public boolean loginUser() throws IOException{

		UserRB userRB = new UserRB();

		try {
			userLogin = userRB.loginUser(user);

			if (null != userLogin){
				((HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true)).setAttribute(AuthFilter.LOGIN_AUTHENTICATION, true);
				FacesContext faces = FacesContext.getCurrentInstance();  
			    ExternalContext context = faces.getExternalContext(); 

			    if (true == userLogin.isAdmin()){
			    	context.redirect(AuthFilter.PATH_CONTROL_PANEL);
			    } else {
			    	context.redirect(AuthFilter.PATH_CONTROL_USER);
			    }
			    
			} else {
				FacesMessage message = new FacesMessage(AuthFilter.ERROR_LOGIN);
				FacesContext context = FacesContext.getCurrentInstance();
				context.addMessage(null, message);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
		
		return true;		
	}
	
	public String logout(){
	    FacesContext fc = FacesContext.getCurrentInstance();  
        HttpSession session = (HttpSession)fc.getExternalContext().getSession(false);  
        session.invalidate();
		return "logout";
	}
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
}
